package cn.udrm.elasticsearch.fileread;

import org.apache.poi.hslf.extractor.PowerPointExtractor;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape;
import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * 读取幻灯片文件内容
 * @author xurongbei
 */
public class PPTReadContent {

    public static String getPptContent(File file) throws IOException {
        FileInputStream fis=new FileInputStream(file);
        PowerPointExtractor powerPointExtractor=new PowerPointExtractor(fis);
        return powerPointExtractor.getText();
    }

    public static String getPptxContent(File file) throws IOException {
        StringBuffer stringBuffer=new StringBuffer();
        FileInputStream fis=new FileInputStream(file);
        XMLSlideShow xmlSlideShow = new XMLSlideShow(fis);
        List<XSLFSlide> slides = xmlSlideShow.getSlides();
        for(XSLFSlide slide:slides){
            CTSlide rawSlide = slide.getXmlObject();
            CTGroupShape gs = rawSlide.getCSld().getSpTree();
            CTShape[] shapes = gs.getSpArray();
            for(CTShape shape:shapes){
                CTTextBody tb = shape.getTxBody();
                if(null==tb){
                    continue;
                }
                CTTextParagraph[] paras = tb.getPArray();
                for(CTTextParagraph textParagraph:paras){
                    CTRegularTextRun[] textRuns = textParagraph.getRArray();
                    for(CTRegularTextRun textRun:textRuns){
                        stringBuffer.append(textRun.getT());
                    }
                }
            }
        }
        fis.close();
        return stringBuffer.toString();
    }

}
